import  Mock  from "mockjs";
// Mock.mock('/api/user/list','get',()=>{ return [] })

var data = {};

// 生成数据
if(localStorage.getItem('user_list')){
    data = JSON.parse(localStorage.getItem('user_list'))
}else{
    // 生成数据
    data = Mock.mock({
        "list|4":[
            {
                id:'@id',
                name:'@cname',
                'age|20-30':1,
                'sex|1':false,
                'phone|13000000000-19999999999':1,
                email:'@email',
                address:'@county(true)'
            }
        ]
    })

        //保存数据到本地存储
        localStorage.setItem('user_list',JSON.stringify( data ))
}
Mock.mock('/api/user/list','get',()=>{  
    //返回数据
    return data;
})

// 删除接口
Mock.mock('/api/user/delete','post',(req)=>{
    // 接收参数 ，req.body 是字符串格式，需要转为json对象
    var {id} = JSON.parse(req.body);
    // 通过id找到要删除得那一条数据，执行删除
    var i = data.list.findIndex((item)=>{
        return item.id == id;
    })
    if(i!=-1){
        data.list.splice(i,1);
        localStorage.setItem('user_list',JSON.stringify(data));
    }
    return {status:200,msg:'删除成功!',list:data.list}
})

// 详情接口
Mock.mock('/api/user/looklist','post',(req)=>{
    var {id} = JSON.parse(req.body);
    var i = data.list.findIndex((item)=>{
        return item.id == id;
    })
    if(i!=-1){
        // console.log(data.list[i]);
        return data.list[i]
        // var lookarr = data.list;
        // console.log(lookarr)
    }
})

// 修改接口
Mock.mock('api/user/editlist','post',(req)=>{
    var {id,name,phone,address,email} = JSON.parse(req.body);
    console.log(id);
    data.list.forEach((item)=>{
        if(item.id == id){
            item.name=name;
            item.phone=phone;   
            item.address=address;
            item.email=email 
        }
    })

    localStorage.setItem('user_list',JSON.stringify(data));
})

var  user = [
     {phone:'17791168227', password:'1234'}
]
// 登录接口
Mock.mock("/api/user/login","post",(req)=>{
     let {phone,password} = JSON.parse(req.body);
     if(phone==='17791168227'&&password==="1234"){
      return{
       status:200,
       msg:"登陆成功",
       phone:phone,
       password:password
      }
     }else{
       return{
        status:400,
        msg:"登陆失败",
       }
     }
    }) 


// 增加接口
Mock.mock("/api/user/add","post",(req)=>{

    // console.log(req)
    var {id,name,phone,address,email,age,sex} = JSON.parse(req.body);
    var obj = {
        id:id,
        name:name,
        phone:phone,
        address:address,
        email:email,
        age:age,
        sex:sex,
    }
    // console.log(id);
    // data.list.forEach((item)=>{
    //     if(item.id == id){
    //         item.name=name;
    //         item.phone=phone;   
    //         item.address=address;
    //         item.email=email 
    //     }
    // })
    data.list.unshift(obj)
    console.log(obj);
    localStorage.setItem('user_list',JSON.stringify(data));
     
    // return (111)

})